jQuery(function($) {

    $("#progressbarAttachments").progressbar();

    $("#progressbarIssues").progressbar();

    var doAjax = function() {
        $.ajax({
            type: "GET",
            url: eventsUrl,
            dataType: "json",
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                   $('#messageList').append("<span style='color: red;'>Ajax error, textStatus: " + textStatus + ", errorThrown: " + errorThrown + "</span><br/>");
                    },
            success: doTask
        });
    }

    var totalSize = 0;
    var downloadedSize = 0;
    var totalIssues = 0;
    var createdIssues = 0;

    var doTask = function(data, textStatus) {
        var progressEvents = data.progressEvents;
        var again = true;
        for (var i = 0; i < progressEvents.length; i++) {
            var progressEvent = progressEvents[i];
            if (progressEvent.eventType == -1) {
                //error
                $('#messageList').append("<span style='color: red;'>" + progressEvent.message + "</span><br/>");
                again = false;
            } else if (progressEvent.eventType == 0) {
                //finish
                $('#messageList').append("<span style='color: green;'>" + progressEvent.message + "</span><br/>");
                again = false;
            } else if (progressEvent.eventType == 1) {
                //message
                $('#messageList').append(progressEvent.message + '<br/>');
            } else if (progressEvent.eventType == 2) {
                //update size
                downloadedSize += progressEvent.size;
                var progress = downloadedSize * 100 / totalSize;
                $('#progressbarAttachments').progressbar('option', 'value', progress);
            } else if (progressEvent.eventType == 3) {
                //total size
                totalSize = progressEvent.size;
            } else if (progressEvent.eventType == 4) {
                //total number of issues
                totalIssues = progressEvent.size;
            } else if (progressEvent.eventType == 5) {
                //issue was created
                createdIssues ++;
                var progressIssues = createdIssues * 100 / totalIssues;
                $('#progressbarIssues').progressbar('option', 'value', progressIssues);
            }
            var scrollHeight = $('#messageList').attr("scrollHeight");
            $('#messageList').attr("scrollTop", scrollHeight);
        }
        if (again) {
            setTimeout(doAjax, 1000);
        }
    };

    setTimeout(doAjax, 1000);
});